<template>
  <el-select v-model="sel" multiple placeholder="请选择" style="width:100%;" @change="onChange">
    <el-option v-for="item in options" :key="item.id" :label="`${item.name?item.name:'未命名'+item.id}[${item.startTime}-${item.endTime}]`" :value="`${item.name}-${item.startTime}-${item.endTime}`">
    </el-option>
  </el-select>
</template>
<script>
import {getList} from '@/api/timeSegment'
export default {
    props: {
        value: {
            type: [String, null],
            default: null
        }
    },
    watch: {
        value: {
            handler(nv) {
                if(nv) {
                    // "[{\"name\":\"测试1\",\"startTime\":\"14:53:00\",\"endTime\":\"15:53:00\"}]
                    const list = JSON.parse(nv);
                    let arr = []
                    list.forEach(item => {
                        let time = `${item.name}-${item.startTime}-${item.endTime}`
                        arr.push(time)
                    })
                    this.sel = arr;
                }else{
                    this.sel = []
                }
            },
            immediate: true
        }
    },
    data() {
        return {
            options: [],
            sel: null
        }
    },
    created() {
        this.getList()
    },
    methods: {
        async getList() {
            try {
                const res = await getList({page: 1, pageSize: 999});
                this.options = res.data;
            } catch (error) {
                
            }
        },
        onChange(e) {
            let list = []
            if(e) {
                e.forEach(item => {
                    const arr = item.split('-');
                    const [name, startTime, endTime] = arr;
                    list.push({name, startTime, endTime})
                })
            }
            this.$emit('input', JSON.stringify(list))
        }
    }
}
</script>